const axios = require("axios");
const express = require("express");
const { Op } = require("sequelize");
const router = express.Router();

const { User } = require("../models");
const { success, failure } = require("../utils/response");

/**
 * 获取用户信息 by openId
 */
router.post("/getByOpenID", async (req, res) => {
  const { openId } = req.body;

  try {
    let user = await User.findOne({
      where: {
        openId: {
          [Op.eq]: openId,
        },
      },
    }).then((user) => filterUserInfo(user));

    // 用户存在
    if (!user) return success(res, "获取用户失败", null);

    success(res, "获取用户成功", user);
  } catch (error) {
    failure(res, error);
  }

  /**
   * 用户不存在，获取手机号
   * https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/user-info/phone-number/getPhoneNumber.html#%E8%B0%83%E7%94%A8%E6%96%B9%E5%BC%8F
   * 返回值
   "data": {
        "errcode": 0,
        "errmsg": "ok",
        "phone_info": {
            "phoneNumber": "18956253745",  // 国外手机带区号
            "purePhoneNumber": "18956253745",  // 完全不带区号 
            "countryCode": "86",
            "watermark": {
                "timestamp": 1736055807,
                "appid": "wx04cc1ae564e62510"
            }
        }
    }
   */
  // try {
  //   console.log("🚀 ~ router.post ~ phoneCode:", phoneCode);
  //   console.log("🚀 ~ router.post ~ accessToken:", accessToken);
  //   console.log("🚀 ~ router.post ~ openId:", openId);

  //   const { phoneData } = await axios.post(
  //     `https://api.weixin.qq.com/wxa/business/getuserphonenumber?access_token=${accessToken}`,
  //     {
  //       code: phoneCode,
  //       openid: openId,
  //     }
  //   );
  //   const phoneNumber = phoneData?.phone_info?.purePhoneNumber;
  //   // 获取手机号失败
  //   if (!phoneNumber) {
  //     console.log("获取手机号失败", phoneData);

  //     return success(res, "获取手机号失败", null);
  //   }

  //   // 获取手机号成功 查询用户
  //   user = await User.findOne({
  //     where: {
  //       phone: {
  //         [Op.eq]: phoneNumber,
  //       },
  //     },
  //   });
  //   // 用不户存在则创建
  //   if (!user) {
  //     user = await User.create({ phone: phoneNumber, openId: openId, role: 0 });
  //   }

  //   return success(res, "获取用户成功", user);
  // } catch (error) {
  //   failure(res, error);
  // }
});

/**
 * 1. 通过 jscode 获取 openId https://developers.weixin.qq.com/miniprogram/dev/OpenApiDoc/user-login/code2Session.html
 * 2. 通过 openId 查询 Users 表，获取用户信息后返回
 * 3. 没有用户则，通过 openId 获取 access_key
 * 4. 通过 access_key openId phoneCode 获取手机号
 * 5. 通过手机号查询 Users 表，获取用户信息
 * 6. 没有用户则，创建用户后返回
 *
 * AppID wx04cc1ae564e62510
 * AppSecret d61558a5bbc4727463724a9475669289
 */

/**
 * 创建用户 by openId,phone
 */
router.post("/createByOpenId", async (req, res) => {
  const { openId, phone } = req.body;
  if (!openId || !phone) return success(res, "缺少openId或手机号", null);

  try {
    // 查询用户是否存在，
    let user = await User.findOne({
      where: {
        phone: { [Op.eq]: phone },
      },
    });

    // 存在则修改openId
    if (user) {
      user = await user.update({ openId }).then((user) => filterUserInfo(user));
      success(res, "创建用户成功", user);
      return;
    }

    // 不存在则创建
    user = await User.create({ phone, openId }).then((user) =>
      filterUserInfo(user)
    );
    success(res, "创建用户成功", user);
  } catch (error) {
    if (error.message === "Validation error") {
      return failure(res, new Error("手机号或openId重复"));
    }
    failure(res, error);
  }
});

/**
 * 获取用户信息 by phone，password
 */
router.post("/getByPassword", async (req, res) => {
  const { phone, password } = req.body;
  const where = { phone: { [Op.eq]: phone }, password: { [Op.eq]: password } };

  try {
    const user = await User.findOne({ where }).then((user) =>
      filterUserInfo(user)
    );
    success(res, "获取用户成功", user);
  } catch (error) {
    failure(res, error);
  }
});

/**
 * 创建用户 by password
 */
router.post("/createByPassword", async (req, res) => {
  const { phone, password } = req.body;

  try {
    const user = await User.create({ phone, password }).then((user) =>
      filterUserInfo(user)
    );
    success(res, "创建用户成功", user);
  } catch (error) {
    if (error.message === "Validation error") {
      return failure(res, new Error("手机号重复"));
    }
    failure(res, error);
  }
});

function filterUserInfo(user) {
  return {
    id: user.id,
    phone: user.phone,
    openId: user.openId,
    role: user.role,
  };
}

module.exports = router;
